import time
import sys

from ConfigLoader import *
from accountManager import *
from instanceManager import *

# 初始化 class
configLoaderManager = configLoader()
mainWareHouse = wareHouse()

def javaCheck() -> any:
    cmdResultIO = os.popen("java --version | awk 'NR==1 {print $2}'")
    cmdResult = cmdResultIO.read()
    cmdResultIO.close()

    if cmdResult != "":
        return cmdResult
    else:
        return False

def preInit():
    os.system("clear")
    print("   . [LitsLoad] Preinit... ")
    print("   * [LitsLoad] Loading user config <userConfig.json> file... ", end="")

    # 读取 LitsMine 设置
    uncommitDataFileID = \
        configLoaderManager.loadFile("./Config/userConfig.json")  # 读取 json 文件并且获取文件存储 ID
    commitDataFileID = \
        configLoaderManager.processingData(uncommitDataFileID, mainWareHouse, autoCommit=True)  # 处理数据并且提交数据
    mainWareHouse.userGlobalSittings["commitDictID"] = commitDataFileID  # 提交提交ID --> 主仓库(mainWareHouse)

    print("   * [LitsLoad] Loading <instance.json> file... ", end="")

    # 读取 Minecraft 实例
    uncommitDataFileID = \
        configLoaderManager.loadFile("./Config/instance.json") # 读取 json 文件并且获取文件存储 ID
    commitDataFileID = \
        configLoaderManager.processingData(uncommitDataFileID, mainWareHouse, autoCommit=True) # 处理数据并且提交数据
    mainWareHouse.minecraftInstances["commitDictID"] = commitDataFileID # 提交提交ID --> 主仓库(mainWareHouse)
    print("(Complete)") # 完成

    print("   * [LitsLogs] Load complete data Type is", type(configLoaderManager.getData(commitDataFileID, mainWareHouse)))
    print("   * [LitsLogs] Loading <account.json> file... ", end="")

    # 读取 Minecraft 用户账号信息
    uncommitDataFileID = \
        configLoaderManager.loadFile("./Config/account.json") # 读取 json 文件并且获取文件存储 ID
    commitDataFileID = \
        configLoaderManager.processingData(uncommitDataFileID, mainWareHouse, autoCommit=True)
    mainWareHouse.minecraftAccounts["commitDictID"] = commitDataFileID # 提交提交ID --> 主仓库(mainWareHouse)
    print("(Complete)") # 完成

    print("   * [LitsLogs] Load complete data Type is", type(configLoaderManager.getData(commitDataFileID, mainWareHouse)))
    print("   * [LitsLogs] Load task all complete, now processing move dict task... ", end="")

    # 移动数据(UserConfig)
    commitDataFileID = mainWareHouse.userGlobalSittings["commitDictID"] - 2  # 获取提交 ID
    dataBuffer = \
        configLoaderManager.getData(commitDataFileID, mainWareHouse)  # 获取提交的词典(Dict)
    mainWareHouse.userGlobalSittings["dictContents"] = dataBuffer  # 将获取的词典信息添加到 --> 主仓库(mainWareHouse)
    configLoaderManager.removeCommit(commitDataFileID, mainWareHouse)  # 清理提交内容
    mainWareHouse.userGlobalSittings["commitDictID"] = None  # 移除提交 ID

    # 移动数据(MinecraftInstance)
    commitDataFileID = mainWareHouse.minecraftInstances["commitDictID"] # 获取提交 ID
    dataBuffer = \
        configLoaderManager.getData(commitDataFileID, mainWareHouse) # 获取提交的词典(Dict)
    mainWareHouse.minecraftInstances.clear()
    mainWareHouse.minecraftInstances = dataBuffer # 将获取的词典信息添加 --> 主仓库(mainWareHouse)
    configLoaderManager.removeCommit(commitDataFileID, mainWareHouse) # 清理提交内容
    mainWareHouse.minecraftInstances["commitDictID"] = None # 移除提交 ID

    # 移动数据(MinecraftAccounts)
    commitDataFileID = mainWareHouse.minecraftAccounts["commitDictID"]  # 获取提交 ID
    dataBuffer = \
        configLoaderManager.getData(commitDataFileID, mainWareHouse)  # 获取提交的词典(Dict)
    mainWareHouse.minecraftAccounts.clear()
    mainWareHouse.minecraftAccounts = dataBuffer  # 将获取的词典信息添加 --> 主仓库(mainWareHouse)
    configLoaderManager.removeCommit(commitDataFileID, mainWareHouse)  # 清理提交内容
    mainWareHouse.minecraftAccounts["commitDictID"] = None  # 移除提交 ID
    print("(3/3)(Complete)")  # 完成

    print("   * [LitsLogs] Check java... "); javaVersion = javaCheck()
    if type(javaVersion) != str:
        print("   * [LitsLogs] Java is not found, please install java.")
        sys.exit(1)
    else:
        print("   * [LitsLogs] Java is found, version is: ", end="")
        print(javaVersion, end="")

    # 加载完成
    if mainWareHouse.userGlobalSittings["dictContents"]["preinitWait"]:
        print("   * [LitsLogs] Preinit complete(3 seconds after run main progarm)!"); time.sleep(3); os.system("clear")
    else:
        print("   * [LitsLogs] Preinit complete(3 seconds after run main progarm)!"); os.system("clear")

# 主函数
if __name__ == '__main__':
    # 初始化
    preInit()

    print("  * ======================================================== *")
    print("  |                        LitsMine                          |")
    print("  |           _     _ _       __  __ _                       |")
    print("  |          | |   (_) |_ ___|  \/  (_)_ __   ___            |")
    print("  |          | |   | | __/ __| |\/| | | '_ \ / _ \\           |")
    print("  |          | |___| | |_\__ \ |  | | | | | |  __/           |")
    print("  |          |_____|_|\__|___/_|  |_|_|_| |_|\___|           |")
    print("  |                                                          |")
    print("  |            *------------- Info -------------*            |")
    print("  |                       Version 1.0.2                      |")
    print("  |                 Powered By NodeSheep Lib                 |")
    print("  |                   Made By LittleSheep_                   |")
    print("  |               Life is short, I use Python                |")
    print("  |                                                          |")
    print("  * --------------- Press Enter key continue --------------- *")
    input("  [ --> ")

    os.system("clear")

    if not mainWareHouse.userGlobalSittings["dictContents"]["canReset"]:
        accountManagerTool = accountManager()

        # 创建 accountList
        mainWareHouse.minecraftAccounts["accountList"] = []

        accountManagerTool.welcomeTitle()
        accountManagerTool.coreUI(True, mainWareHouse)

        # 更换 canReset 值
        mainWareHouse.userGlobalSittings["dictContents"]["canReset"] = True
        # 保存文件
        configLoaderManager.saveData("./Config/userConfig.json", mainWareHouse.userGlobalSittings["dictContents"])

    while True:

        os.system("clear")

        # 显示主菜单
        print("  * ----------------------- MainMenu ----------------------- *")
        print("  |  1. Run instance                                  (User) |")
        print("  |  2. Manager instance                              (User) |")
        print("  |  3. Account Manager                               (User) |")
        print("  |  S. Settings                                      (User) |")
        print("  |  Q. Exit                                          (User) |")
        print("  * ----------------------- Selector ----------------------- *")
        selectorGet = input("  [ --> ")

        os.system("clear")

        # 退出函数
        if selectorGet == "q" or selectorGet == "Q":
            # 保存文件
            print("  * [LitsMine] Saving file... ")
            os.remove("./Config/account.json")
            os.remove("./Config/instance.json")
            os.remove("./Config/userConfig.json")

            configLoaderManager.saveData("./Config/account.json", mainWareHouse.minecraftAccounts)
            configLoaderManager.saveData("./Config/instance.json", mainWareHouse.minecraftInstances)
            configLoaderManager.saveData("./Config/userConfig.json", mainWareHouse.userGlobalSittings["dictContents"])

            os.system("clear")

            # 退出
            break

        # 运行函数
        if selectorGet == "1":
            pass

        # 管理实例函数
        if selectorGet == "2":

            # 初始化 class
            mainInstanceManager = instanceManager()

            # 显示欢迎语
            mainInstanceManager.welcomeTitle()

        # 管理账号函数
        if selectorGet == "3":
            accountManagerTool = accountManager()

            accountManagerTool.welcomeTitle()
            accountManagerTool.coreUI(False, mainWareHouse)

        # 设置函数:
        if selectorGet == "S":
            pass

    # 退出程序
    sys.exit(0)